import time
from django.conf import settings
from c21_qrcode.common import common
from c21_qrcode.common import redis_service


def _add_domain(qrcode_url):
    # s3填坑，之前的cdn失效了
    invalid_cdn = 'http://2ed3559cebdf8.cdn.sohucs.com/'
    if qrcode_url.startswith('http://'):
        qrcode_url = qrcode_url.replace(invalid_cdn, settings.S3_CDN)
    # 之后变成了https(兼容脏数据)
    elif qrcode_url.startswith('https://'):
        pass
    else:
        # 之后的存储不在存储domain
        qrcode_url = settings.S3_CDN + qrcode_url
    return qrcode_url


def _save_qrcode_data(appid, short_s, data, ex=None):
    slurl = redis_service.SLurl()
    if not ex:
        ex = settings.VALIDITY_PERIOD_APPID.get(appid)
    else:
        max_ex = settings.VALIDITY_PERIOD_APPID.get(appid)
        ex = ex if ex < max_ex else max_ex
    res = slurl.set_only_key(short_s, data, ex=ex)
    if not res:
        error_info = 'err:ShortUrl Repeat,short_url:{0},long_url:{1}'.format(
            short_s, data['long_url'])
        raise Exception(error_info)


def get_qrcode_info(long_url, appid, icon_url, need_icon=0, ex=None):
    '''
    函数功能:
        生成短连接信息
    参数:
        long_url: str
        appid: str
        icon_url: str
        need_icon: int  0:don't need icon, 1: need icon
    返回:
        dict:{
            short_url
            qrcode_url
        }
    '''
    short_s = common.only_short_url(
        long_url, pro=settings.URL_ED[appid])
    if not short_s:
        return False
    q_version = 5
    q_ec = 'H'
    q_box_size = 9
    if appid in settings.ULTRA_SHORT_APPID:
        q_params = settings.ULTRA_SHORT_PARAM[appid]
        short_s = short_s[0:4]
        q_version = q_params['q_version']
        q_ec = q_params['q_ec']
        q_box_size = q_params['q_box_size']
    slurl = redis_service.SLurl()
    value = slurl.get(short_s)
    short_url = settings.SHORT_URL_PREFIX[appid] + short_s

    if not value or icon_url != value['icon_url']:
        user_qrcode, MIME = common.get_qrcode(
            short_url, avatar_url=icon_url, need_avatar=int(need_icon),
            q_version=q_version, q_ec=q_ec, q_box_size=q_box_size,
            fill_color="#112443", add_avatar=True)
        user_qrcode_name = 'qrcode' + '_' + short_s + '.png'
        # folder = 'qrcode/'
        # common.upload_file2s3(file=user_qrcode, folder=folder,
        #                       filename=user_qrcode_name, MIME=MIME)
        qrcode_url = common.download_to_oss(
            file=user_qrcode, filename=user_qrcode_name, MIME=MIME)
        # qrcode_url = folder + user_qrcode_name + '?flyer=' + str(time.time())
        value = {
            'icon_url': icon_url,
            'qr_url': qrcode_url,
            'long_url': long_url
        }
        _save_qrcode_data(appid, short_s, value, ex=ex)
    else:
        qrcode_url = value['qr_url']
    qrcode_url = qrcode_url
    return {'short_url': short_url, 'qrcode_url': qrcode_url}
